<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="kYQuniuaRZuL9fq0DATfL7extAwcqWG6Ki286ZMcpak">
  <meta name="baidu-site-verification" content="code-MRqS7DOO9x">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha256-DfWjNxDkM94fVBWx1H5BMMp0Zq7luBlV8QRcSES7s+0=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blogwxb.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.11.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":true,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="一、路由复用路由复用要在相对应的路由中添加的是在components里面，不是children。例如： 12345678910&amp;#123;    path: &quot;&#x2F;&quot;,    name: &quot;Home&quot;,    components: &amp;#123; &#x2F;&#x2F;这里是components不是component      default: Home,      &amp;quot">
<meta property="og:type" content="article">
<meta property="og:title" content="vue的路由复用和导航守卫">
<meta property="og:url" content="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/index.html">
<meta property="og:site_name" content="会飞的猪9527">
<meta property="og:description" content="一、路由复用路由复用要在相对应的路由中添加的是在components里面，不是children。例如： 12345678910&amp;#123;    path: &quot;&#x2F;&quot;,    name: &quot;Home&quot;,    components: &amp;#123; &#x2F;&#x2F;这里是components不是component      default: Home,      &amp;quot">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/0.png">
<meta property="og:image" content="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/1.png">
<meta property="article:published_time" content="2020-04-21T01:05:11.000Z">
<meta property="article:modified_time" content="2022-10-07T15:14:02.083Z">
<meta property="article:author" content="wxb">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/0.png">


<link rel="canonical" href="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/","path":"vue的路由复用和导航守卫/","title":"vue的路由复用和导航守卫"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>vue的路由复用和导航守卫 | 会飞的猪9527</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <!-- Google Analytics -->
  <script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('send', 'pageview');
  </script>
  <script async src='https://www.google-analytics.com/analytics.js'></script>
  <!-- End Google Analytics -->

  <!-- Baidu Analytics -->
  <script async src = 'https://zz.bdstatic.com/linksubmit/push.js'></script>
  <!-- End Baidu Analytics -->

<link rel="alternate" href="/atom.xml" title="会飞的猪9527" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">会飞的猪9527</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">32</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">5</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">91</span></a></li><li class="menu-item menu-item-commonweal"><a href="/404" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">一、路由复用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB"><span class="nav-number">2.</span> <span class="nav-text">二、导航守卫</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%881%EF%BC%89%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB"><span class="nav-number">2.1.</span> <span class="nav-text">（1）全局前置守卫</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%882%EF%BC%89%E5%85%A8%E5%B1%80%E5%90%8E%E7%BD%AE%E9%92%A9%E5%AD%90"><span class="nav-number">2.2.</span> <span class="nav-text">（2）全局后置钩子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%883%EF%BC%89%E8%B7%AF%E7%94%B1%E7%8B%AC%E4%BA%AB%E7%9A%84%E5%AE%88%E5%8D%AB"><span class="nav-number">2.3.</span> <span class="nav-text">（3）路由独享的守卫</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%884%EF%BC%89%E7%BB%84%E4%BB%B6%E5%86%85%E7%9A%84%E5%AE%88%E5%8D%AB"><span class="nav-number">2.4.</span> <span class="nav-text">（4）组件内的守卫</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%885%EF%BC%89%E5%AE%8C%E6%95%B4%E7%9A%84%E5%AF%BC%E8%88%AA%E8%A7%A3%E6%9E%90%E6%B5%81%E7%A8%8B"><span class="nav-number">2.5.</span> <span class="nav-text">（5）完整的导航解析流程</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wxb"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">wxb</p>
  <div class="site-description" itemprop="description">主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">91</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/dearDreamWeb" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;dearDreamWeb" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      推荐
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.ruanyifeng.com/blog/" title="https:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;" rel="noopener" target="_blank">阮一峰的网络日志</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://nav.blogwxb.cn/" title="https:&#x2F;&#x2F;nav.blogwxb.cn&#x2F;" rel="noopener" target="_blank">轩辕导航</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/dearDreamWeb" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blogwxb.cn/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="wxb">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="会飞的猪9527">
      <meta itemprop="description" content="主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="vue的路由复用和导航守卫 | 会飞的猪9527">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          vue的路由复用和导航守卫
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-04-21 09:05:11" itemprop="dateCreated datePublished" datetime="2020-04-21T09:05:11+08:00">2020-04-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2022-10-07 23:14:02" itemprop="dateModified" datetime="2022-10-07T23:14:02+08:00">2022-10-07</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <!-- <span id="busuanzi_value_page_pv"></span> -->
      <span id="views_text"></span>
    </span>
</div>


        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="一、路由复用"><a href="#一、路由复用" class="headerlink" title="一、路由复用"></a>一、路由复用</h1><p>路由复用要在相对应的路由中添加的是在<font color="#f40">components</font>里面，不是children。<br>例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">path</span>: <span class="string">&quot;/&quot;</span>,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;Home&quot;</span>,</span><br><span class="line">    <span class="attr">components</span>: &#123; <span class="comment">//这里是components不是component</span></span><br><span class="line">      <span class="attr">default</span>: <span class="title class_">Home</span>,</span><br><span class="line">      <span class="string">&quot;Delivery&quot;</span>: <span class="title class_">Delivery</span>,</span><br><span class="line">      <span class="string">&quot;History&quot;</span>: <span class="title class_">History</span>,</span><br><span class="line">      <span class="string">&quot;OrderingGuide&quot;</span>: <span class="title class_">OrderingGuide</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<span id="more"></span>
<p>App组件部分</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;el-row <span class="keyword">class</span>=<span class="string">&quot;main&quot;</span>&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span>    <span class="comment">//没有指定路由，当访问哪个路由显示哪个相对应的组件</span></span><br><span class="line">&lt;/el-row&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">el-row</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">el-col</span> <span class="attr">:md</span>=<span class="string">&quot;8&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">&quot;Delivery&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span>  // 这三个有指定路由，会显示指定的组件</span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">el-col</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">el-col</span> <span class="attr">:md</span>=<span class="string">&quot;8&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">&quot;History&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">el-col</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">el-col</span> <span class="attr">:md</span>=<span class="string">&quot;8&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">&quot;OrderingGuide&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">el-col</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">el-row</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>运行结果图：<br><img data-src="/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/0.png" alt="0.png"></p>
<p><img data-src="/vue%E7%9A%84%E8%B7%AF%E7%94%B1%E5%A4%8D%E7%94%A8%E5%92%8C%E5%AF%BC%E8%88%AA%E5%AE%88%E5%8D%AB/1.png" alt="1.png"></p>
<font color="#f40">
    解释一下上面这个例子：
    Home组件对应的路径是"/"，也就是根路径。App组件是首页组件，因为只有Home组件有components的配置的复用组件，所以只有在根路径才会显示那三个复用的路由组件。也就是上面运行结果表现出来的。
</font>

<h1 id="二、导航守卫"><a href="#二、导航守卫" class="headerlink" title="二、导航守卫"></a>二、导航守卫</h1><p>记住参数或查询的改变并不会触发进入&#x2F;离开的导航守卫。你可以通过观察 $route 对象来应对这些变化，或使用 beforeRouteUpdate 的组件内守卫。</p>
<h2 id="（1）全局前置守卫"><a href="#（1）全局前置守卫" class="headerlink" title="（1）全局前置守卫"></a>（1）全局前置守卫</h2><p>你可以使用 router.beforeEach 注册一个全局前置守卫：<br><font color="#f40">在配置完router后面注册router.beforeEach。</font></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> <span class="title class_">VueRouter</span>(&#123; ... &#125;)</span><br><span class="line"></span><br><span class="line">router.<span class="title function_">beforeEach</span>(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>当一个导航触发时，全局前置守卫按照创建顺序调用。守卫是异步解析执行，此时导航在所有守卫 resolve 完之前一直处于 等待中。<br>每个守卫方法接收三个参数：</p>
<ul>
<li>to: Route: 即将要进入的目标 路由对象</li>
<li>from: Route: 当前导航正要离开的路由</li>
<li>next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。<ul>
<li>next(): <font color="#f40">进行管道中的下一个钩子</font>。如果全部钩子执行完了，则导航的状态就是 confirmed (确认的)。</li>
<li>next(false): <font color="#f40">中断当前的导航</font>。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮)，那么 URL 地址会重置到 from 路由对应的地址。</li>
<li>next(‘&#x2F;‘) 或者 next({ path: ‘&#x2F;‘ }): <font color="#f40">跳转到一个不同的地址。当前的导航被中断，然后进行一个新的导航</font>。你可以向 next 传递任意位置对象，且<font color="#f40">允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项</font>。</li>
<li>next(error):  如果传入 next 的参数是一个 Error 实例，则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。<br>确保要调用 next 方法，否则钩子就不会被 resolved。</li>
</ul>
</li>
</ul>
<h2 id="（2）全局后置钩子"><a href="#（2）全局后置钩子" class="headerlink" title="（2）全局后置钩子"></a>（2）全局后置钩子</h2><p>你也可以注册全局后置钩子，然而和守卫不同的是，这些钩子<font color="#f40">不会接受 next 函数也不会改变导航本身</font>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">router.<span class="title function_">afterEach</span>(<span class="function">(<span class="params">to, <span class="keyword">from</span></span>) =&gt;</span> &#123;   <span class="comment">// 没有next参数</span></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="（3）路由独享的守卫"><a href="#（3）路由独享的守卫" class="headerlink" title="（3）路由独享的守卫"></a>（3）路由独享的守卫</h2><p>你可以在<font color="#f40">路由配置上直接定义</font> beforeEnter 守卫：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> <span class="title class_">VueRouter</span>(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/foo&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: <span class="title class_">Foo</span>,</span><br><span class="line">      <span class="attr">beforeEnter</span>: <span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>这些守卫与全局前置守卫的方法参数是一样的。</p>
<h2 id="（4）组件内的守卫"><a href="#（4）组件内的守卫" class="headerlink" title="（4）组件内的守卫"></a>（4）组件内的守卫</h2><p>最后，你可以在路由组件内直接定义以下路由导航守卫：</p>
<ul>
<li>beforeRouteEnter</li>
<li>beforeRouteUpdate (2.2 新增)</li>
<li>beforeRouteLeave<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Foo</span> = &#123;</span><br><span class="line">  <span class="attr">template</span>: <span class="string">`...`</span>,</span><br><span class="line">  beforeRouteEnter (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 在渲染该组件的对应路由被 confirm 前调用</span></span><br><span class="line">    <span class="comment">// 不！能！获取组件实例 `this`</span></span><br><span class="line">    <span class="comment">// 因为当守卫执行前，组件实例还没被创建</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeRouteUpdate (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 在当前路由改变，但是该组件被复用时调用</span></span><br><span class="line">    <span class="comment">// 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，</span></span><br><span class="line">    <span class="comment">// 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeRouteLeave (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 导航离开该组件的对应路由时调用</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">beforeRouteEnter 守卫 不能 访问 <span class="variable language_">this</span>，因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。</span><br><span class="line">不过，你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调，并且把组件实例作为回调方法的参数。</span><br><span class="line">beforeRouteEnter (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">  <span class="title function_">next</span>(<span class="function"><span class="params">vm</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 通过 `vm` 访问组件实例</span></span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
注意<br> <font color="#f40">beforeRouteEnter 是支持给 next 传递回调的唯一守卫</font>。对于 <font color="#f40">beforeRouteUpdate 和 beforeRouteLeave</font> 来说，<font color="#f40">this 已经可用了</font>，所以不支持传递回调，因为没有必要了。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">beforeRouteUpdate (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">  <span class="comment">// just use `this`</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">name</span> = to.<span class="property">params</span>.<span class="property">name</span></span><br><span class="line">  <span class="title function_">next</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 <font color="#f40">next(false)</font> 来取消。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">beforeRouteLeave (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">  <span class="keyword">const</span> answer = <span class="variable language_">window</span>.<span class="title function_">confirm</span>(<span class="string">&#x27;Do you really want to leave? you have unsaved changes!&#x27;</span>)</span><br><span class="line">  <span class="keyword">if</span> (answer) &#123;</span><br><span class="line">    <span class="title function_">next</span>()</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">next</span>(<span class="literal">false</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="（5）完整的导航解析流程"><a href="#（5）完整的导航解析流程" class="headerlink" title="（5）完整的导航解析流程"></a>（5）完整的导航解析流程</h2><ol>
<li>导航被触发。</li>
<li>在失活的组件里调用离开守卫。</li>
<li>调用全局的 <font color="#f40">beforeEach</font> 守卫。</li>
<li>在重用的组件里调用 <font color="#f40">beforeRouteUpdate</font> 守卫 (2.2+)。</li>
<li>在路由配置里调用 <font color="#f40">beforeEnter</font>。</li>
<li>解析异步路由组件。</li>
<li>在被激活的组件里调用 <font color="#f40">beforeRouteEnter</font>。</li>
<li>调用全局的 <font color="#f40">beforeResolve</font> 守卫 (2.5+)。</li>
<li>导航被确认。</li>
<li>调用全局的 <font color="#f40">afterEach</font> 钩子。     </li>
<li>用创建好的实例调用 beforeRouteEnter 守卫中传给 <font color="#f40">next</font> 的回调函数。</li>
</ol>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关博客</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-08-20</div>
      <div class="popular-posts-title"><a href="path-resolve和path-join/" rel="bookmark">path.resolve和path.join</a></div>
      
    </li>
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-04-17</div>
      <div class="popular-posts-title"><a href="vue中的filters过滤器/" rel="bookmark">vue中的filters过滤器</a></div>
      
    </li>
  </ul>


    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="wxb 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.png" alt="wxb 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/atom.xml">
          <span class="icon">
            <i class="fa fa-rss"></i>
          </span>

          <span class="label">RSS</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"># Vue</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/vue%E4%B8%AD%E7%9A%84filters%E8%BF%87%E6%BB%A4%E5%99%A8/" rel="prev" title="vue中的filters过滤器">
                  <i class="fa fa-chevron-left"></i> vue中的filters过滤器
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Express%E5%A4%84%E7%90%86%E5%89%8D%E7%AB%AF%E5%8A%A8%E6%80%81%E8%AF%B7%E6%B1%82%EF%BC%88-id%EF%BC%89/" rel="next" title="Express处理前端动态请求（/:id）">
                  Express处理前端动态请求（/:id） <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wxb</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <!-- <span id="busuanzi_value_site_uv"></span> -->
        <span id="uv-views"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <!-- <span id="busuanzi_value_site_pv"></span> -->
        <span id="pv-views"></span>
      </span>
    </span>
</div><script src="/js/diy_footer.js"></script>
  <div class="powered-by">
    <div style="display: inline-flex;align-items: center;">
      <img src="/images/copyrihgt.png" alt="wxb 微信" with='20' height='20' style="margin-right: 4px;">
      <a href="https://beian.miit.gov.cn/" target="_blank">浙ICP备2022027687号</a>
    </div>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/medium-zoom/1.0.6/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"dearDreamWeb","repo":"blogwxb.github.io","client_id":"86685a6104f8e6ba5827","client_secret":"7cf015e84bbe755bde20c8aca767977e316304ad","admin_user":"dearDreamWeb","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.min.js","integrity":"sha256-Pmj85ojLaPOWwRtlMJwmezB/Qg8BzvJp5eTzvXaYAfA="},"path_md5":"882d54db5b7dea064e85b3ab0d00d8e3"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>

</body>
</html>
